package com.example.fitapp.activity.activity;

import android.content.ContentUris;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.example.fitapp.activity.R;
import com.example.fitapp.activity.bean.MySerializable;
import com.example.fitapp.activity.http.api.user.UserEditHeader;
import com.example.fitapp.activity.http.api.user.UserEditName;
import com.example.fitapp.activity.http.api.user.UserLogin;
import com.example.fitapp.activity.http.util.ApiListener;
import com.example.fitapp.activity.http.util.ApiUtil;
import com.example.fitapp.activity.http.util.ImagePost;
import com.example.fitapp.activity.utils.L;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.Response;

public class UsEditActivity extends AppCompatActivity {
    public static final int CHOOSE_PHOTO = 2;
    private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");

    private MySerializable mySerializable;


    private LinearLayout editHeader;
    private LinearLayout editName;
    private TextView userName;
    private ImageView user_header;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_us_edit);
        Intent intent = getIntent();
        mySerializable = (MySerializable) intent.getSerializableExtra("userData");

        user_header = findViewById(R.id.user_header);
        editName = findViewById(R.id.edit_name);
        userName = findViewById(R.id.user_name);

        Glide.with(getApplicationContext()).load(mySerializable.getUser_header()).into(user_header);
        userName.setText(mySerializable.getName());

        user_header.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                L.d("打开相册");
                open_photo();
            }
        });

        editName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent editInputIntent= new Intent(UsEditActivity.this,EditInputActivity.class);
                editInputIntent.putExtra("extra_title","修改名称");
                editInputIntent.putExtra("extra_value","frankin");
                startActivityForResult(editInputIntent,3);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case 3:
                if(resultCode == RESULT_OK){
                    String returnedData = data.getStringExtra("data_return");
                    userName.setText(returnedData);
                    new UserEditName(returnedData).post(new ApiListener() {
                        @Override
                        public void success(ApiUtil apiUtil) {
                            UserEditName api = (UserEditName)apiUtil;
                            String response = api.mResponse;
                        }

                        @Override
                        public void failure(ApiUtil apiUtil) {
                        }
                    });
                }
                break;
            case CHOOSE_PHOTO:
                if (resultCode == RESULT_OK){
                    handleImageOnKitKat(data);
                }
                break;
        }
    }

    // 打开相册
    private void open_photo() {
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent, CHOOSE_PHOTO); // 打开相册
    }

    // 4.4以上的手机版本(不同手机版本的照片处理
    private void handleImageOnKitKat(Intent data) {
        String imagePath = null;
        Uri uri = data.getData();
        if (DocumentsContract.isDocumentUri(this, uri)){
            // 如果是document 类型的uri，则通过document id处理
            String docId = DocumentsContract.getDocumentId(uri);
            if ("com.android.providers.media.documents".equals(uri.getAuthority())){
                String id =docId.split(":")[1]; // 解析出数字格式的id
                String selection = MediaStore.Images.Media._ID + "=" + id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
            } else if ("com.android.providers.downloads.documents".equals(uri.getAuthority())){
                Uri contenUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),Long.valueOf(docId));
                String ImagePath = getImagePath(contenUri, null);
            }
        }else if ("content".equalsIgnoreCase(uri.getScheme())){
            imagePath = getImagePath(uri, null);
        }else if ("file".equalsIgnoreCase(uri.getScheme())){
            imagePath = uri.getPath();
        }
        File file = new File(imagePath);
        Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
        pushPhtot("pushuPhoto",file,bitmap);
    }

    // 获取图片文件路径
    private String getImagePath(Uri uri, String selection) {
        String path = null;
        // 通过Uri 和 selection 来获取真实的图片路径
        Cursor cursor = getContentResolver().query(uri,null,selection,null,null);
        if (cursor != null){
            if (cursor.moveToFirst()){
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return path; // 返回真是的图片文件路径
    }

    // post上传图片
    private void pushPhtot(String name, File file, final Bitmap bitmap) {
        RequestBody fileBody = RequestBody.create(MEDIA_TYPE_PNG, file);

        final RequestBody requestBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("file",file.getName(),fileBody)
                .addFormDataPart("name",name)
                .build();
            ImagePost.post("/v1/common/upload", requestBody, new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Log.d("MainActivity","asda"+e);
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String stringdata = response.body().string();
                    String urlStr = null;
                    try {
                        urlStr =  new JSONObject(stringdata).getString("url");
                        Log.i("urlStr",urlStr);
                        String finalUrlStr = urlStr;
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Glide.with(UsEditActivity.this).load("https://fitapp.dashingdog.cn" + finalUrlStr).into(user_header);
                            }
                        });
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    // urlStr就是成功回调的路径
                    Log.d("ssss",""+  urlStr);
                    new UserEditHeader(urlStr+"").post(new ApiListener() {
                        @Override
                        public void success(ApiUtil apiUtil) {
                            UserEditHeader api = (UserEditHeader)apiUtil;
                            String response = api.mResponse;
                        }

                        @Override
                        public void failure(ApiUtil apiUtil) {
                        }
                    });

                }
            });
    }

}
